/**
 * 系统附件管理初始化
 */
var Attachment = {
    id: "AttachmentTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1,
    oldData:null
};

/**
 * 初始化表格的列
 */
Attachment.initColumn = function () {
    return [
        {field: 'selectItem', radio: false},
            {title: '主键', field: 'id', visible: true, align: 'center', valign: 'middle'},
            {title: '文件名', field: 'fileName', visible: true, align: 'center', valign: 'middle'},
            {title: '文件大小', field: 'fileSize', visible: true, align: 'center', valign: 'middle',formatter:function(size){
            	return size>1024*1024?(Math.round(size/1024/1024)+"MB"):(size>1024?(Math.round(size/1024)+"KB"):(size+"B"))
            }},
            {title: '上传时间', field: 'uploadTime', visible: true, align: 'center', valign: 'middle'},
            {title: '保存方式', field: 'saveTo', visible: true, align: 'center', valign: 'middle',formatter:function(saveTo){
            	return saveTo=="filesystem"?"服务器":(saveTo=="db"?"数据库":saveTo);
            }},
            {title: '文件说明', field: 'description', visible: true, align: 'center', valign: 'middle'},
            {title: '文件格式', field: 'fileType', visible: true, align: 'center', valign: 'middle'},
            {title: '文件',    visible: true, align: 'center', valign: 'middle',formatter:function(val,row){
            	var iconClz="fa fa-download";
            	var hrefClz="downloadHref";
            	var normalDownload = true;
            	if(!!row.fileType){
            		
	            	if(row.fileType.startsWith("image/")){
	            		iconClz="fa fa-file-photo-o";
	            		hrefClz="photoHref";
	            		normalDownload=false;
	            	}
	            	else if(row.fileType.startsWith("video/")){
	            		iconClz="fa fa-file-video-o";
	            		hrefClz="videoHref";
	            		normalDownload=false;
	            	}
	            	else if(row.fileType.startsWith("audio/")){
	            		iconClz="fa fa-file-audio-o";
	            		hrefClz="audioHref";
	            		normalDownload=false;
	            	}
            	}
            	return '<a href="'+(normalDownload?(Feng.ctxPath+"/api/attachment/download?attachmentId="+row.id):'javascript:void(0);')
            			+'" class="'+hrefClz+'">'
            			+'<i class="'+iconClz+'" aria-hidden="true"></i>'
            			+'</a>';
            },events:{
            	'click .photoHref':function(e,val,row){
            		Feng.infoDetail(row.fileName,"<img src='"+Feng.ctxPath+"/api/attachment/download?attachmentId="+row.id+"' style='max-height:560px;max-width:850px;'></img>",'900px', '600px');
            	},
	            'click .videoHref':function(e,val,row){
	            	Feng.infoDetail(row.fileName,"<video controls  style='width: 800px !important; height:500px !important; object-fit:contain;'>"
  +"<source src='"+Feng.ctxPath+"/api/attachment/download?attachmentId="+row.id+"' type='"+row.fileType+"'>"
  +"<p>Your browser doesn't support HTML5 video. Here is a <a target='_blank' href='"+Feng.ctxPath+"/api/attachment/download?attachmentId="+row.id+"'>link to the video</a> instead.</p>"
+"</video>");
	            },
            	'click .audioHref':function(e,val,row){
            		Feng.infoDetail(row.fileName,"<audio controls style='width: 100% !important;   object-fit:contain;'>"
            				+"<source src='"+Feng.ctxPath+"/api/attachment/download?attachmentId="+row.id+"' type='"+row.fileType+"'>"
            				+"<p>Your browser doesn't support HTML5 audio. Here is a <a  target='_blank' href='"+Feng.ctxPath+"/api/attachment/download?attachmentId="+row.id+"'>link to the audio</a> instead.</p>"
            				+"</audio>", "600px", "200px");
            	}
            }}
    ];
};

/**
 * 检查是否选中
 */
Attachment.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length == 0){
        Feng.info("请先选中表格中的某一记录！");
        return false;
    }else{
        Attachment.selectedItems = selected;
        Attachment.seItem = selected[0];
        return true;
    }
};

/**
 * 点击添加系统附件
 */
Attachment.openAddAttachment = function () {
    var index = layer.open({
        type: 2,
        title: '添加系统附件',
        area: ['800px', '420px'], //宽高
        fix: false, //不固定
        maxmin: true,
        content: Feng.ctxPath + '/attachment/attachment_add'
    });
    this.layerIndex = index;
};

/**
 * 打开查看系统附件详情
 */
Attachment.openAttachmentDetail = function () {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '系统附件详情',
            area: ['800px', '420px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/attachment/attachment_update/' + Attachment.seItem.id
        });
        this.layerIndex = index;
    }
};

/**
 * 删除系统附件
 */
Attachment.delete = function () {
    if (this.check() ) {
    	Feng.confirm("该附件可能被其他业务模块使用，请谨慎删除！",function(){
    		var ajax = new $ax(Feng.ctxPath + "/api/attachment/remove?attachmentId="+Attachment.seItem.id, function (data) {
    			Feng.success("删除成功!");
    			Attachment.table.refresh();
    		}, function (data) {
    			Feng.error("删除失败!" + data.responseJSON.message + "!");
    		});
    		ajax.type="delete";
    		ajax.start();
    	});
    }
};
/**
 * 移动系统附件
 */
Attachment.moveAttachment = function (type) {
    if (this.check() ) {
		var total = Attachment.selectedItems.length;
		var num = 0;
		Attachment.selectedItems.forEach(item=>{
			console.log(item)
			var formData = new FormData();
			formData.set("id", item.id);
			formData.set("saveTo", type);
			num++;
		  //提交信息
		    var ajax = new $ax(Feng.ctxPath + "/api/attachment/update", function(data){
		        if(data.success === true){
			        Feng.info("移动完成"+num+"/"+total);
				}else{
		        	Feng.error("修改失败!" + data.msg + "!");
				}
		    },function(data){
		        Feng.error("修改失败!" + data.responseJSON.message + "!");
		    });
		    ajax.setProcessData(false)
			    .setContentType(false)
			    .setData(formData);
		    ajax.start();
		});
		Attachment.table.refresh();
    }
};

/**
 * 查询系统参数列表
 */
Attachment.search = function () {
	var fileName =$("#condition").val();
	$.getJSON(Feng.ctxPath+"/api/attachment",function(res){
		Attachment.oldData = res.data;
		var newdata = Attachment.oldData.filter(function(e){ return !fileName || e.fileName.toUpperCase().indexOf(fileName.toUpperCase())>-1;});
		Attachment.table.btInstance.bootstrapTable("load",newdata);
	});
};

$(function () {
    var defaultColunms = Attachment.initColumn();
    var table = new BSTable(Attachment.id, "/api/attachment", defaultColunms, function(res){
    	 Attachment.oldData = res.data;
    	return res.data;
    });
    table.method="get";
    table.setPaginationType("client");
    Attachment.table = table.init();
});
